﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using EventLogger.Dns;
using System.ServiceModel;
using System.Net.NetworkInformation;

namespace EventLogger.Service
{
    public partial class LoggerServiceClient
    {
        public static LoggerServiceClient ConnectToDefault(string baseDomainName)
        {            
            var domain = string.Format("_eventlogger._tcp.{0}", baseDomainName);
            var resolver = new Resolver();

            var response = resolver.Query(domain, QType.SRV);

            RecordSRV record = response.Answers.Select(r => r.RECORD).OfType<RecordSRV>().FirstOrDefault();
            if (record == null)
            {
                throw new Exception();
            }

            var client = new LoggerServiceClient();

            var address = string.Format("http://{0}:{1}/LoggerService.svc", record.TARGET, record.PORT);

            client.Endpoint.Address = new EndpointAddress(address);
            client.ChannelFactory.Endpoint.Address = new EndpointAddress(address);

            client.Open();

            return client;
        }

        public static LoggerServiceClient ConnectToDefault()
        {
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            return ConnectToDefault(ipProperties.DomainName);
        }
    }
}
